// pages/radar/radar.js
var wxCharts = require('../../utils/wxcharts.js');
const app = getApp()
var mtabW;
var ringChart = null;

/**
 * 聊天
 */
var webim = require('../../utils/webim_wx.js');
var webimhandler = require('../../utils/webim_handler.js');

// global.webim = webim;



Page({

    /**
     * 页面的初始数据
     */
    data: {
        current: 0,
        currentActive: 0,
        slideOffset: 0,
        tabW: 0,
        setInter: '',
        num: 1,
        radarPower: true,
        list: [{
                name: "访客"
            },
            {
                name: "聊天"
            },
        ],
        /**
         * 聊天
         */
        Identifier: '',
        UserSig: '',
    },
    onLoad: function(options) {
        app.station_id = ''
        // app.chatLogin = false

        wx.getSystemInfo({
            success: res => {
                mtabW = res.windowWidth / 4; //设置tab的宽度
                var offsetW = mtabW / 2;
                this.setData({
                    tabW: mtabW,
                    slideOffset: offsetW
                })
            }
        });
        wx.getStorageSync('user') && this.loadData()
        this.setData({
            my_id: wx.getStorageSync('mid')
        })
    },
    onShow() {
        app.http.get('city/tiny-station/check-auth').then(res => {
            this.setData({
                is_vip: res.data.auth,
                count: res.data.count,
                open: res.data.open
            })
            if (res.data.auth) {
                this.loadContact()
            }
        })
    },
    toArticle(e) {
        console.log(e, 'eeeeeeeeeeeeee')

    },
    onHide() {
        this.uploadListener()
    },
    onUnload() {
        this.uploadListener()
    },
    loadData() {
        this.loadVisit()
        // this.checkUserAuth()
    },
    /**关闭监听 */
    uploadListener() {
        var listeners = {
            "status": 1
        }
        webim.changeListener(listeners);
    },
    /**
     * 加载访客
     */
    loadVisit() {
        let {
            nextFlag = true, page = 0, loading = false, visitList = []
        } = this.data
        if (loading || !nextFlag) {
            return
        }
        loading = true
        this.setData({
            loading: true
        })

        app.http.post('city/tiny-station/get-customer-trail-v2?page=' + page).then(q => {
            page++
            loading = false
            visitList.push(...q.data.customerData)
            nextFlag = q.data.nextFlag
            this.setData({
                page,
                loading,
                visitList,
                nextFlag
            })
            wx.stopPullDownRefresh()
        }).catch(err => {
            this.setData({
                loading: false
            })
        })
    },
    /**
     * IM登录
     */
    //权限验证
    // checkUserAuth() {
    //     app.http.post('tencent-im/get-auth-web').then(q => {
    //         this.setData({
    //             radarPower: q.data,
    //         })
    //         wx.stopPullDownRefresh()
    //     })
    // },
    loadContact() {
        app.http.post('city/tiny-station/login-im').then(q => {
            this.setData({
                UserSig: q.data.sig,
            })
            wx.stopPullDownRefresh()
            this.initIM();
        })
    },
    navClick(e) {
        const {
            current
        } = e.currentTarget.dataset
        var offsetW = e.currentTarget.offsetLeft + (this.data.tabW / 2);
        this.setData({
            current: current,
            slideOffset: offsetW
        })

    },
    titleClick(e) {
        this.setData({
            currentActive: e.currentTarget.dataset.index,
        })
    },
    /**
     * 是否关闭提示
     */
    isRadar() {
        this.setData({
            radarPower: true
        })
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {
        this.setData({
            page: 0,
            nextFlag: true,
            loading: false,
            visitList: [],
        })
        wx.getStorageSync('user') && this.loadData()
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {
        wx.getStorageSync('user') && this.loadVisit()
    },

    /**
     * 聊天
     */
    login: function(cb) {
        var that = this;
        tls.login({
            success: function(data) {
                that.setData({
                    Identifier: 'll' + wx.getStorageSync('mid'),
                    UserSig: data.UserSig
                })
                cb();
            }
        });
    },
    initIM: function() {
        var that = this;
        //当前用户身份
        var Config = {
            sdkappid: 1400114382,
            accountType: 31956,
            accountMode: 0 //帐号模式，0-表示独立模式，1-表示托管模式
        };
        var loginInfo = {
            'sdkAppID': Config.sdkappid, //用户所属应用id,必填
            'appIDAt3rd': Config.sdkappid, //用户所属应用id，必填
            'accountType': Config.accountType, //用户所属应用帐号类型，必填
            'identifier': 'll' + wx.getStorageSync('mid'), //当前用户ID,必须是否字符串类型，选填
            'identifierNick': wx.getStorageSync('user').nickName, //当前用户昵称，选填
            "headurl": wx.getStorageSync('user').avatarUrl,
            'userSig': that.data.UserSig, //当前用户身份凭证，必须是字符串类型，选填
            //'userSig': wx.getStorageSync('UserSig_'),
            'loginPage': 2 //2表示雷达页面进入,此页面进入需要获取最近联系人
        };
        //监听事件
        var listeners = {
            "onMsgNotify": function(msg) {
                webimhandler.onMsgNotify(msg, function(msgs) {
                    // that.receiveMsgs(msgs);

                })
            }, //监听新消息事件，必填


        };

        //其他对象，选填
        var options = {
            'isAccessFormalEnv': true, //是否访问正式环境，默认访问正式，选填
            'isLogOn': false //是否开启控制台打印日志,默认开启，选填
        };
        //初始化了聊天对象，联系人页面设为-1，聊天页面设为相应的id
        webimhandler.init('0', 0)
        console.log(loginInfo, '1111111111')
        webimhandler.sdkLogin(loginInfo, listeners, options,

            //获取info后回掉，将所有联系人展示在页面上
            function(recent_user) {
                console.log(loginInfo, '222222222222')

                app.chatLogin = true

                that.setData({
                    contactList: recent_user.SessionItem,
                })
                console.log(recent_user, 'xxxxxxxxxxx')
                //最近联系人，recent_user为读取的最近联系人信息
                //console.error(recent_user)
                //当前聊天好友的历史消息(读取15条)
                webimhandler.getC2CHistoryMsgs(
                    //success回调函数,x为读取的消息
                    function(x) {
                        for (var i in x)
                            that.receiveMsgs(x[i])
                    }

                )
            });
    },
})